package com.xyxe.domain.strategy.service.rule.chain.impl;


import com.xyxe.domain.strategy.repository.IStrategyRepository;
import com.xyxe.domain.strategy.service.armory.IStrategyDispatch;
import com.xyxe.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.xyxe.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.xyxe.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 * 权重
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;
    @Resource
    private IStrategyDispatch strategyDispatch;
    private Long userScore = 0L;
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());

        // 1.根据用户ID查询用户抽奖消耗的积分值，本章先写死为固定值，后续从数据库中查询
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        Map<Long, String> analyticalValue = getAnalyticalValue(ruleValue);
        if (null == analyticalValue || analyticalValue.isEmpty()) {
            return null;
        }

        // 2.转换key值并排序
        ArrayList<Long> analyticalValueSortedKeys = new ArrayList<>(analyticalValue.keySet());
        Collections.sort(analyticalValueSortedKeys);

        // 3.找出最小符合的权重值
        Long nextValue = null;
        for (Long key : analyticalValueSortedKeys) {
            if (userScore < key) {
                break;
            }
            nextValue = key;
        }
        // 3.1.达到某一权重
        if (null != nextValue) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValue.get(nextValue));
            log.info("抽奖责任链-权重接管 userId:{} strategyId:{} ruleModel:{} awardId:{}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        // 4.过滤其他责任链
        log.info("抽奖责任链-权重放行 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> resultMap = new HashMap<>();

        for (String ruleValueGroup : ruleValueGroups) {
            //检查输入是否为空
            if (ruleValueGroup == null || ruleValueGroup.isEmpty()) return resultMap;

            //分割字符串获取键和值
            String[] splitRuleValue = ruleValueGroup.split(Constants.COLON);
            if (splitRuleValue.length != 2) {
                throw new IllegalArgumentException("Rule value is not correct: " + ruleValue);
            }
            resultMap.put(Long.parseLong(splitRuleValue[0]), ruleValueGroup);
        }
        return resultMap;
    }
}
